package com.htlwk.javapractice;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @ClassName GenericGoods
 * @Description TODO
 * @Author liaowenxiong
 * @Date 2024/12/25 19:52
 * @Version 1.0
 */
public class GenericGoods<T> {
    private T goods;
    private String info_goods;

    public GenericGoods(T goods) {
        this.goods = goods;
        try {
            this.info_goods = setData(goods);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private String setData(T goods) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        StringBuilder sb = new StringBuilder();
        String getterMethodName;
        String fieldName;
        Method method;
        StringBuilder info_goods = new StringBuilder();

        Field[] fields = goods.getClass().getDeclaredFields();
        if (fields.length > 0) {
            for (Field field : fields) {
                fieldName = field.getName();
                sb.append(fieldName).append("#");
                if (fieldName.length() > 1) {
                    getterMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                } else {
                    getterMethodName = "get" + fieldName.toUpperCase();
                }

                method = goods.getClass().getMethod(getterMethodName);
                info_goods.append(fieldName).append("=").append(method.invoke(goods)).append("&");
            }
            info_goods = new StringBuilder(info_goods.substring(0, info_goods.length() - 1));
        }
        return info_goods.toString();
    }

    public T getGoods() {
        return goods;
    }

    public void setGoods(T goods) {
        this.goods = goods;
    }

    public String getInfo_goods() {
        return info_goods;
    }

    public void setInfo_goods(String info_goods) {
        this.info_goods = info_goods;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        GenericGoods<?> that = (GenericGoods<?>) o;
        return Objects.equals(goods, that.goods) && Objects.equals(info_goods, that.info_goods);
    }

    @Override
    public int hashCode() {
        return Objects.hash(goods, info_goods);
    }
}
